# -*- coding:utf-8 -*-

from urllib2 import Request, urlopen, URLError, HTTPError
import socket

def basic_http_get(url, data = None, http_headers={}):
    if data:
        url = url + '?' + data
    req = Request(url)
    if http_headers:
        for i, k in http_headers.items():
            req.add_header(i, k)
    try:
        response = urlopen(req, timeout=10)
        res = response.read()
        return ''.join(response.headers.headers) + '\r\n' + res
    except HTTPError, e:
        return "Error code: %s, HTTP headers: %s"%(e.code, e.headers)
    except socket.timeout, e:
        return "Error socket timeout!\n%s\r\n"%e
    except:
        return

def basic_http_post(url, data, http_headers={}):
    req = Request(url)
    if http_headers:
        for i, k in http_headers.items():
            req.add_header(i, k)
    try:
        response = urlopen(req, data, timeout=10)
        return ''.join(response.headers.headers) + '\r\n' + response.read()
    except HTTPError, e:
        return "Error code: %s, HTTP headers: %s"%(e.code, e.headers)
    except socket.timeout, e:
        return "Error socket timeout!\n%s"%e
    except:
        return

def test_get():
    url = 'http://192.168.3.1/html/index.html'
    headers = {'a':'b', 'c':'d', 'cookie':'name=value'}
    data = 'abc=1&3234'
    print basic_http_get(url, http_headers=headers)
def test_post():
    url = 'http://192.168.3.1/html/index.html'
    headers = {'a': 'b', 'c': 'd'}
    data = 'abc=1&3234=44455'
    print basic_http_post(url, data, headers)


if __name__ == '__main__':
    test_get()
